package org.ricks.log;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author chenwei
 * @Description:异步日志分发器
 * @date 2023/1/916:30
 */
public class AsyncLoggerDisruptor extends Thread {

    /**
     * 异步记录日志线程池
     */
    private final ScheduledExecutorService scheduledExecutor;

    AsyncLoggerDisruptor() {
        scheduledExecutor = new ScheduledThreadPoolExecutor(1, r -> {
            Thread t = new Thread(r, "async-log"); //如果设置守护线程，就会出现日志还没有记录。日志线程被销毁的情况
            return t;
        });
        Runtime.getRuntime().addShutdownHook(this);
    }

    /**
     * 发布一个日志事件.
     * <p>就是丢给线程池就OK了，由消费线程去处理存档与显示</p>
     *
     * @param event 日志事件
     */
    public void publish(AsyncLogEvent event) {
        scheduledExecutor.execute(event);
    }

    /**
     * 安全停服
     */
    public void shutdown() {
        try {
            RicksLogger.info("最后一条LOG?");
            scheduledExecutor.shutdown();
            scheduledExecutor.awaitTermination(1, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            // 最大等待时间为1分钟，还没写完，那就丢了吧...
            System.err.println("等待1分钟，还没写完。日志缺失");
        }
    }


    @Override
    public void run() {
        System.err.println("开始销毁日志线程。。。。。");
        LogManager.shutdown();
    }
}
